package com.cjg.xiancheng;

public class threadPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new  Watcher(tv).start();
    }
}

//生产者  演员
class Player extends Thread{
    TV tv ;

    @Override
    public void run() {
        for (int i = 0; i <10 ; i++) {
            tv.play("yan ");
        }
    }

    public Player(TV tv) {
        this.tv = tv;
    }
}
//消费者 观众
class Watcher extends  Thread{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
          tv.watch();
        }
    }

    TV tv ;

    public Watcher(TV tv) {
        this.tv = tv;
    }
}
class TV{
    //节目
    String voice ;
    // 演员表演 ,观众等待 T  ,观众观看,演员等待  F
    boolean flag = true;
    //表演的方法
    public synchronized void play(String voice){
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了"+voice);

        //通知唤醒
        this.notify();
        //更新节目
        this.voice=voice;
        //改变状态
        this.flag=!this.flag;
    }


    public synchronized  void watch(){
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了"+voice);

        //通知演员表演了
        this.notify();
        this.flag=!this.flag;
    }
}